<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/11
 * Time: 17:05
 */

namespace app\api\controller;


use app\api\Base2Controller;
use think\Db;

/**
 * Class Tonggao
 * @package app\api\controller
 */
// extends BaseController
class Tianzhuan extends Base2Controller
{
    /**
     * 获取品牌
     */
    public function getBrand()
    {
        if (!empty($class_id = $typeid = intval(input('typeid')))) {
            #首先找到所有的分类id
            $goods_class = db('goodsclass')->where(['gc_id'=>$typeid,'gc_show'=>1])->find();

            #如果有父级id
            if(!empty($goods_class['gc_parent_id'])){
                $superior_goods_class =  db('goodsclass')->where(['gc_id'=>$goods_class['gc_parent_id'],'gc_show'=>1])->find();
                $class_id = $superior_goods_class['gc_id'] .','. $class_id;
                
                if(!empty($superior_goods_class['gc_parent_id'])){
                    $upper_superior_goods_class =  db('goodsclass')->where(['gc_id'=>$superior_goods_class['gc_parent_id'],'gc_show'=>1])->find();
                    $class_id = $upper_superior_goods_class['gc_id']  .','. $class_id;
                }
            }
            $parms = [ 
                'brand_apply' => 1,
                'gc_id' => ['in',"{$class_id}"]
            ];
            $result = Db::name('brand')->field('brand_id,brand_name,brand_initial')
                ->where($parms)
                ->order('brand_sort desc')->select();
        } else {
            $result = Db::name('brand')->field('brand_id,brand_name,brand_initial')
                ->where(['brand_apply' => 1])
                ->order('brand_sort desc')->select();
        }
        return json_success_return($result);
    }

    //添钻根据分类名称获取相应的品牌
    public function search_goods_brand()
    {
        $data = input('post.');
        if (empty($data['equipment_id'])) {
            return json_fail_return('参数错误');
        }

        #获取设备库详情
        $equipment_info = db('new_equipment')->where(['id' => $data['equipment_id']])->find();

        // 转为数组遍历查下面的品牌
        $result = [];
        if (!empty($equipment_info['equipment_band_id'])) {
            $brand_array = explode(",", $equipment_info['equipment_band_id']);
            foreach ($brand_array as $key => $value) {
                $res = db('new_equipment_brand')
                    ->where(['equipment_brand_id' => $value])
                    ->field('equipment_brand_id,brand_name,brand_id,equipment_id')
                    ->find();
                if ($res) {
                    $result[] = $res;
                }
            }
        }
        return json_success_return($result);
    }

    /**
     * 获取问题
     */
    public function getQution()
    {
        $result = Db::name('question')->field('id,title')
            ->where(['status' => 1])->select();
        return json_success_return($result);
    }


    /**
     * 搜索设备库信息
     */
    public function getSearchName()
    {
        $data = input('post.');
        if ($name = input('search_name')) {
            $condition['goods_name'] = array('like', "%" . $name . "%");
        }
        $search_gc_id1 = input('param.search_gc_id1', '');
        $search_gc_id2 = input('param.search_gc_id2', '');
        $search_gc_id3 = input('param.search_gc_id3', '');
        if ($search_gc_id1) {
            $condition['gc_one_id'] = ['eq', $search_gc_id1];
        }
        if ($search_gc_id2) {
            $condition['gc_two_id'] = ['eq', $search_gc_id2];
        }
        if ($search_gc_id3) {
            $condition['gc_three_id'] = ['eq', $search_gc_id3];
        }

        $condition['equipment_del'] = 0;
        $condition['equipment_status'] = 1;
        $equipmentModel = new \app\common\model\Equipment();
        $equipment_list = $equipmentModel->getNquipmentList($condition, 10);

        return json_success_return($equipment_list);
    }


    /**
     * 设备列表
     */
    public function shebeiList()
    {
        if (empty($userid = $this->user_id)) {
            return json_fail_return('请登录');
        }
        $where['member_id'] = $userid;
        if (empty($status = intval(input('status')))) {
            $where['equipment_status'] = 0;
        } else {
            $where['equipment_status'] = array('neq', 0);
        }
        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;

        $result = Db::name('new_equipment')->alias('ne')
            ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
            ->where($where)
            ->field('ne.*,neb.*,neb.brand_name as b_name')
            ->limit($offset, $pagesize)
            ->order('id desc')
            ->select();
        foreach ($result as $key => $value) {
            if ($value['equipment_status'] == 0) {
                $result[$key]['statusName'] = '待审核';
            } elseif ($value['equipment_status'] == 1) {
                $result[$key]['statusName'] = '完成';
            } elseif ($value['equipment_status'] == 2) {
                $result[$key]['statusName'] = '未通过';
            } else {
                $result[$key]['statusName'] = '未知状态';
            }
        }
        return json_success_return($result);
    }


    /**
     * Notes:我要舔砖  添加
     * User: shen
     * Date: 2020/5/6
     * Time: 14:43
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addBricks()
    {
        $data = input('post.');
        if (
            empty($data['goods_name']) || empty($data['class_id']) || empty($data['b_name'])
            || empty($data['specifications']) || empty($data['type_model'])
        ) {
            return json_fail_return('请正确输入信息');
        }

        #处理后台已经添加过了的话 就提示不要重复添加   shen 2020.5.6
        $new_equipment_where = [
            'goods_name' => $data['goods_name'],
            'gc_id' => $data['class_id'],
            'status' => 1,
            'is_store' => 0,
            'equipment_status' => 1,
            'equipment_del' => 0,
        ];
        $new_equipment_info = db('new_equipment')->where($new_equipment_where)->find();
        if ($new_equipment_info) {
            #主表存在去查品牌表
            $new_equipment_brand_info = db('new_equipment_brand')->where(['brand_name' => $data['b_name'], 'equipment_id' => $new_equipment_info['id']])->find();
            if ($new_equipment_brand_info) {
                #存在去确定规格型号
                $search_content = $data['specifications'] . ',' . $data['type_model'];
                if (strpos($new_equipment_brand_info['spec_value_type'], $search_content)) {
                    return json_fail_return('设备库已存在本设备信息，请勿重复添加');
                }
            }
        }


        //处理分类
        $class = db('goodsclass')->where(['gc_id' => $data['class_id']])->find();
        if (empty($class['gc_parent_id'])) {
            //没父值的话就是一级分类id
            $param['gc_one_id'] = $class['gc_id'];
            $param['gc_id'] = $class['gc_id'];
            $param['class_name'] = $class['gc_name'];
        } else {
            //有父值的话再往上找
            $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
            if (empty($class_one['gc_parent_id'])) {
                $param['gc_one_id'] = $class_one['gc_id'];
                $param['gc_two_id'] = $class['gc_id'];
                $param['gc_id'] = $class['gc_id'];
                $param['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
            } else {
                $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                $param['gc_one_id'] = $class_two['gc_id'];
                $param['gc_two_id'] = $class_one['gc_id'];
                $param['gc_three_id'] = $class['gc_id'];
                $param['gc_id'] = $class['gc_id'];
                $param['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
            }
        }

        $images = json_decode(htmlspecialchars_decode($data['equipment_images']), true); #多张图片，首张图片当主图

        $equipment_images = '';
        foreach ($images as $k => $v) {
            if ($k == 0) {
                $equipment_images = $v;
            }
        }
        #首先加主表信息
        $param['goods_name'] = $data['goods_name'];
        $param['created_at'] = date('Y-m-d H:i:s', time());
        $param['is_store'] = 1;
        $param['equipment_status'] = 0;
        $param['member_id'] = $this->user_id;
        $param['equipment_images'] = $equipment_images;
        $param['equipment_images_array'] = htmlspecialchars_decode($data['equipment_images']);

        $eid = Db::name('new_equipment')->insertGetId($param);

        #加品牌表
        $new_param['brand_name'] = $data['b_name'];
        $new_param['equipment_id'] = $eid;
        $new_param['brand_created_at'] = date('Y-m-d H:i:s', time());
        $new_param['specifications'] = $data['specifications'];
        $new_param['type_model'] = $data['type_model'];

        $bid = db('new_equipment_brand')->insertGetId($new_param);
        db('new_equipment')->where(['id' => $eid])->update(['equipment_band_id' => $bid]);

        return json_success_return([], '已提交信息，请耐心等候审核');
    }


    /**
     * 上传图片
     */
    public function upload()
    {
        if (empty($_FILES['file'])) {
            json_fail_return('请选择图片');
        }
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $upload_info = upload_qiniu('file');
            if ($upload_info['err'] == 0) {
                $name = $upload_info['http'] . '/' . $upload_info['data'];
                return json_success_return($name);
            } else {
                json_fail_return('上传失败');
            }
        } else {
            json_fail_return('请上传正常格式的图片');
        }
    }


    /**
     * 添加添砖  (作废)
     */
    public function addShebei()
    {
        if (
            empty($name = input('name')) || empty($science = input('science'))
            || empty($cateOne = input('cateOne')) || empty($cateTwo = input('cateTwo'))
            || empty($cateThree = input('cateThree'))
            || empty($dismantling_hours = input('dismantling_hours')) || empty($installation_hours = input('installation_hours'))
            || empty($type_model = input('type_model')) || empty($specifications = input('specifications'))
            || empty($question_id = input('question_id'))
            || empty($option = input('option')) || empty($imgs = input('imgs'))
        ) {
            return json_fail_return('请正确输入信息');
        }
        $b_id = input('bid') ? input('bid') : 0;
        if (!$b_id) {
            if (empty($bname = trim(input('bname')))) {
                return json_fail_return('请正确输入信息');
            }
        }
        $class_name = Db::name('goodsclass')
                ->where(['gc_id' => $cateOne])
                ->field('gc_name')
                ->find()['gc_name'] . '>' . Db::name('goodsclass')
                ->where(['gc_id' => $cateTwo])
                ->field('gc_name')
                ->find()['gc_name'] . '>' . Db::name('goodsclass')
                ->where(['gc_id' => $cateThree])
                ->field('gc_name')
                ->find()['gc_name'];
        if ($b_id) {
            $bname = Db::name('brand')->where(['brand_id' => $b_id])->field('brand_name')->find()['brand_name'];
        } else {
            $bname = trim(input('bname'));
        }
        $userid = $this->user_id;
        $data = [
            'goods_name' => $name,
            'gc_id' => $cateThree,
            'class_name' => $class_name,
            'b_id' => $b_id,
            'b_name' => $bname,
            'question_id' => $question_id,
            'specifications' => $specifications,
            'type_model' => $type_model,
            'installation_hours' => $installation_hours,
            'dismantling_hours' => $dismantling_hours,
            'created_at' => date('Y-m-d H:i:s', time()),
            'updated_at' => date('Y-m-d H:i:s', time()),
            'gc_one_id' => $cateOne,
            'gc_two_id' => $cateTwo,
            'gc_three_id' => $cateThree,
            'status' => 1,
            'is_store' => 1,
            'equipment_status' => 0,
            'member_id' => $userid,
            'equipment_del' => 0,
            'equipment_images' => $imgs
        ];
        $eid = Db::name('equipment')->insertGetId($data);
        if ($eid) {
            $optionArr = json_decode(htmlspecialchars_decode($option), true);
            $optionId = [];
            /**
             * 添加部位
             */
            foreach ($optionArr as $key => $value) {
                $optionArr2 = [
                    'content' => $value['content'],
                    'maintenance_hours' => $value['maintenance_hours'],
                    'repair_hours' => $value['repair_hours'],
                    'created_at' => time(),
                    'updated_at' => time(),
                    'lev' => 0,
                    'equipment_id' => $eid
                ];
                $optionId[] = Db::name('equipment_option')->insertGetId($optionArr2);
            }
            /**
             * 添加环境配置
             */
            $scienceId = [];
            $scienceArr = json_decode(htmlspecialchars_decode($science), true);
            foreach ($scienceArr as $key => $value) {
                $scienceArr2 = [
                    'science' => $value,
                    'create_time' => time(),
                    'lev' => 0,
                    'sort' => 0,
                    'equipment_id' => $eid
                ];
                $scienceId[] = Db::name('equipment_science')->insertGetId($scienceArr2);
            }
            if (!$optionId) {
                $msg = '添加成功,部位添加失败!';
            } elseif (!$scienceId) {
                $msg = '添加成功,环境配置添加失败!';
            } else {
                $msg = '添加成功';
            }
            $eid2 = Db::name('equipment')->where(['id' => $eid])->update(['option' => implode(',', $optionId), 'science' => json_encode($scienceId)]);
            if ($eid2) {
                return json_success_return([], $msg);
            } else {
                return json_fail_return('设备添加成功,部位或环境配置添加失败!');
            }
        } else {
            return json_fail_return('添加失败');
        }
    }
}
